package com.tj.collection.db.service.impl;

import com.fqgj.common.utils.DateUtil;
import com.fqgj.common.utils.MD5;
import com.fqgj.common.utils.StringUtils;
import com.fqgj.exception.common.ApplicationException;
import com.tj.collection.db.admin.dao.AdminDAO;
import com.tj.collection.db.admin.dao.AdminTokenDAO;
import com.tj.collection.db.admin.entity.AdminEntity;
import com.tj.collection.db.admin.entity.AdminTokenEntity;
import com.tj.collection.db.domain.Admin;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.UUID;

/**
 * Created with IntelliJ IDEA.
 * User: sm
 * Date: 2017/3/11
 * Time: 下午5:06
 * 登陆服务
 */
@Service
public class AdminLoginService {

    @Autowired
    private AdminDAO adminDAO;

    @Autowired
    private AdminTokenDAO adminTokenDAO;

    /**
     * 登陆 成功则返回对应的用户标识token
     *
     * @param admin
     * @return
     */
    public String adminLogin(Admin admin, String verifyCode1, boolean sso) {
        AdminEntity adminEntity = adminDAO.getByAccount(admin.getAccount());
        checkLoginInfo(admin, adminEntity, null);
        admin.setName(adminEntity.getName());

        AdminTokenEntity adminTokenEntity = adminTokenDAO.getByAdminId(adminEntity.getId());
        if (adminTokenEntity == null) {
//            throw new AuthAdminException("User information is incomplete!");
            adminTokenEntity = new AdminTokenEntity();
            adminTokenEntity.setAccessToken(MD5.md5(UUID.randomUUID().toString()));
            adminTokenEntity.setAdminId(adminEntity.getId());
            adminTokenEntity.setExpireDate(DateUtil.addDate(DateUtil.getPatternDate(new Date(), "yyyy-MM-dd"), 30));
            adminTokenDAO.save(adminTokenEntity);
        } else {
            //通过sso控制是否互踢
            if (sso) {
                adminTokenEntity.setAccessToken(MD5.md5(UUID.randomUUID().toString()));
            }
            adminTokenEntity.setExpireDate(DateUtil.addDate(DateUtil.getPatternDate(new Date(), "yyyy-MM-dd"), 30));
            adminTokenEntity.setGmtModified(new Date());
            adminTokenDAO.update(adminTokenEntity);
        }

        return adminTokenEntity.getAccessToken();
    }

    private void checkLoginInfo(Admin admin, AdminEntity adminEntity, String verifyCode) {
        if (adminEntity == null) {
            throw new ApplicationException("The user does not exist!");
        }

        if ((StringUtils.isNotEmpty(adminEntity.getPassword()) &&
                (adminEntity.getPassword().equals(MD5.md5(admin.getPassword())) || adminEntity.getPassword().equals(admin.getPassword())))
        ) {
        }else{
            throw new ApplicationException("Wrong login info!");
        }
    }
}
